package com.yuanmei.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import static com.yuanmei.common.Utils.TAG;

/**
 * log日志
 */
public class LogFile {
    private static String LOG_FILE;
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.CHINA);

    public static void init(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            LOG_FILE = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "saved_logs.txt";
        } else {// 如果SD卡不存在，就保存到本应用的目录下
            LOG_FILE = context.getFilesDir().getAbsolutePath() + File.separator + "saved_logs.txt";
        }
    }

    public synchronized static void append(String tag, String msg) {
        if (null == LOG_FILE) {
            Log.e(TAG, "logPath == null ，未初始化LogToFile");
            return;
        }
        String log = dateFormat.format(new Date()) + " " +  tag + " " + msg + "\n";
        FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法，不用关闭
        BufferedWriter bw = null;
        try {
            fos = new FileOutputStream(LOG_FILE, true);//这里的第二个参数代表追加还是覆盖，true为追加，flase为覆盖
            bw = new BufferedWriter(new OutputStreamWriter(fos));
            bw.write(log);
            Log.i(TAG, log);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();//关闭缓冲流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
